package com.gonsin.gmessage.logic.mqtt;

import com.gonsin.gmessage.annotations.GMessageEnvironment;
import com.gonsin.gmessage.logic.GMessage;
import com.gonsin.gmessage.logic.client.IClientService;
import com.google.gson.Gson;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.RemoveInfo;
import org.eclipse.paho.mqttv5.client.IMqttMessageListener;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class MqttClientServiceImpl implements InitializingBean {

    @Autowired
    private MqttClientManager mqttClientManager;

    @Autowired
    private IClientService clientService;

    @Override
    public void afterPropertiesSet() throws Exception {
        String topic = "$SYS/brokers/+/clients/#";
        mqttClientManager.subscribe(topic, 1, this::notifications);
    }


    /**
     * 以下topic=activemq.notifications 在 activemq artemis有效
     * 更多信息请查看 <a href="https://activemq.apache.org/components/artemis/documentation/latest/management.html">Management</a>
     * @param message
     */
//    @SneakyThrows
//    @JmsListener(destination = "activemq.notifications", containerFactory = "topicListenerFactory")
    public void notifications(String topic, MqttMessage message){
//        String type = (String) message.getProperty("_AMQ_NotifType");
//        log.info(type);

        if(topic.endsWith("/disconnected")){
            String json = new String(message.getPayload(), StandardCharsets.UTF_8);
            ClientDisconnectDto dto = new Gson().fromJson(json, ClientDisconnectDto.class);
            if(dto.getClientid() != null){
                clientService.notifyClientOffline(dto.getClientid());
            }
        } else if(topic.endsWith("/connected")){
            String json = new String(message.getPayload(), StandardCharsets.UTF_8);
            ClientConnectDto dto = new Gson().fromJson(json, ClientConnectDto.class);
            OnlineDeviceBo bo = OnlineDeviceBo.builder()
                    .connectionId(dto.getClientid())
                    .mac(dto.getUsername())
                    .ip(dto.getIpaddress())
                    .build();
            clientService.notifyClientOnline(bo.getConnectionId(), bo);
        }

//
    }


}
